<template>
  <div>
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-size: 16px;">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i> 后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item>事故列表</el-breadcrumb-item>

    </el-breadcrumb>


    <el-divider></el-divider>

    <!-- 事故添加的说明    -->
    <el-card style="float: left ;width: 100%;height: 100%">
      <el-button type="warning" icon="el-icon-edit" @click="">事故添加说明</el-button>
      <div style="width: 100%;text-align: center;margin-top: -30px">
        <img src="../../../assets/event/picture.png" width="1200" alt="">
      </div>
    </el-card>


    <el-divider></el-divider>




    <el-card style="float: left ;width: 100%;height: 100%">
      <el-divider content-position="left">事故表格</el-divider>
    <!--    添加事件的按钮-->
    <el-button type="warning" icon="el-icon-edit" @click="openAddNewDialog()">添加事故</el-button>

    <!-- 事件列表   -->
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column type="index" label="编号" align="center" width="50"></el-table-column>


      <!-- 显示事故的级别,显示情况根据matterLevel决定   -->
      <el-table-column label="事故级别" width="100" align="center">
        <template slot-scope="scope">
          <el-tag style="background-color: #848784" effect="dark" v-if="scope.row.matterLevel==1"> [小型事故]</el-tag>
          <el-tag style="background-color: #454346" effect="dark" v-if="scope.row.matterLevel==2"> [一般事故]</el-tag>
          <el-tag style="background-color: #000000" effect="dark" v-if="scope.row.matterLevel==3"> [重大事故]</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="olderName" label="老人姓名" width="80" header-align="center"></el-table-column>
      <el-table-column prop="name" label="事故名称" width="100"  header-align="center"></el-table-column>
      <el-table-column prop="info" label="事故详细信息" width="300" header-align="center"></el-table-column>


        <!-- 显示事故的状态,显示情况根据state决定   -->
      <el-table-column label="事故状态" width="100" align="center">
        <template slot-scope="scope">
          <el-tag type="danger" effect="dark" v-if="scope.row.state==0">● 正在审核</el-tag>
          <el-tag type="success" effect="dark" v-if="scope.row.state==1">● 正在处理</el-tag>
          <el-tag type="info" effect="dark" v-if="scope.row.state==2">● 审核通过</el-tag>
        </template>
      </el-table-column>

      <el-table-column prop="checkName" label="审核人" width="100" align="center"></el-table-column>
      <el-table-column prop="checkInfo" label="审核人备注" width="200" header-align="center">
      </el-table-column>
      <el-table-column prop="gmtCreate" :formatter="formaTime" label="发生时间" width="160" align="center">


      </el-table-column>

      <!-- 列表操作栏      -->
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-tooltip class="item" effect="dark"  content="请注意:事故需要经过审核和处理两个阶段, 只有处理完成的事故记录可以删除!" placement="top-start">
          <el-button v-if="scope.row.state==0" type="danger" icon="el-icon-edit"  size="mini"
                     @click="openEditDialog(scope.row)">开始审核</el-button>
          <el-button v-if="scope.row.state==1" type="success" icon="el-icon-edit"  size="mini"
                     @click="openEditDialog(scope.row)">处理完成</el-button>
          <el-button v-if="scope.row.state==2" type="info" icon="el-icon-delete"  size="mini"
                     @click="openDeleteConfirm(scope.row)">删除</el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    </el-card>


    <!-- 弹出的新增事故的对话框 -->
    <el-dialog title= "新增事故"  :visible.sync="addNewFormVisible">
      <el-form :model="addNewForm" :rules="rules" ref="addNewForm">
        <el-form-item label="事故等级" :label-width="formLabelWidth"  prop="matterLevel">
          <el-select v-model="addNewForm.matterLevel"  placeholder="请选择事故等级">
            <el-option label="小型事故" value='1'></el-option>
            <el-option label="一般事故" value='2'></el-option>
            <el-option label="大型事故" value='3'></el-option>
          </el-select>
        </el-form-item>


        <el-form-item label="事故老人" :label-width="formLabelWidth"  prop="olderId">
          <el-select v-model="addNewForm.olderId"  >
            <el-option
                v-for="item in olderListOptions" :key="item.id"
                :label="item.name"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="事故标题" :label-width="formLabelWidth" prop="name">
          <el-input v-model="addNewForm.name" autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item label="事故详细描述" :label-width="formLabelWidth" prop="info">
          <el-input v-model="addNewForm.info" autocomplete="off"></el-input>
        </el-form-item>

      </el-form>



      <!-- 新增事件的按钮       -->
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button type="warning" @click="addNewSubmitForm('addNewForm')">提交事故</el-button>
        <el-button @click="addNewFormVisible = false">取 消</el-button>
      </div>
    </el-dialog>



    <!--  弹出的修改事故的对话框  -->
    <el-dialog style="text-align: center; color: #E6A23C"  :title=this.eventEditTitle :visible.sync="dialogFormVisible">

        <el-descriptions class="margin-top" title="" :column="2" :size="size" border>
          <el-descriptions-item label="事故名称":label-width="formLabelWidth">{{ editForm.name }}</el-descriptions-item>
          <el-descriptions-item label="事故老人":label-width="formLabelWidth">{{ editForm.olderName }}</el-descriptions-item>
          <el-descriptions-item label="事故详情":label-width="formLabelWidth">{{ editForm.info }}</el-descriptions-item>
          <el-descriptions-item label="事故发生时间":label-width="formLabelWidth">{{ editForm.gmtCreate }}</el-descriptions-item>
        </el-descriptions>

        <el-form :model="editForm" :rules="rules" ref="editForm">
          <el-col :span="24">
            <el-card shadow="never">
              <el-form-item :label=this.eventEditLable :label-width="formLabelWidth" prop="checkInfo">
                <el-input type="textarea"  v-model="editForm.checkInfo" autocomplete="off"></el-input>
              </el-form-item>
            </el-card>
          </el-col>
        </el-form>
        <!-- 修改事件的按钮       -->
        <div slot="footer" class="dialog-footer" style="margin: 0">
          <el-button center= true @click="dialogFormVisible = false">取 消</el-button>
          <el-button center= true type="primary" @click="updateSubmitForm('editForm')">提交</el-button>
        </div>
    </el-dialog>
  </div>
</template>


<script>
export default {

  data() {
    return {
      editForm:{

      },
      dialogFormVisible:false,

      //事故编辑窗口显示的标题,由当前事故的状态有关;
      eventStateText:['审核事故', '处理事故'],
      eventEditTitle:'',

      //事故编辑窗口显示的详情询问语句,由当前事故的状态有关;
      eventEditLableOptions:['审核意见','处理结果描述'],
      eventEditLable:'',


      rules: {
        olderId: [{ required: true, message: '请选择发生事故的老人', trigger: 'blur' }],
        name: [{ required: true, message: '请输入事故标题', trigger: 'blur' }, { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }],
        info: [{ required: true, message: '请输入事故详细描述', trigger: 'blur' }, { min: 3, max: 200, message: '长度在 3 到 200 个字符', trigger: 'blur' }],
        checkInfo:[{required: true, message: '请输入审核/完成后详细描述', trigger: 'blur'}],
        matterLevel:[{required: true, message: '请输入事故等级', trigger: 'blur'}],

      },
      olderListOptions:[],

      tableData: [],

      addNewFormVisible: false,
      addNewForm: {
        matterLevel:'',
        olderId:'',
        name: '',
        info:'',
      },
      formLabelWidth: '120px'
    }
  },
  methods: {
    //修改时间格式
    formaTime(row,column) {

      let data = row[column.property]
      let dtime = new Date(data)
      const year = dtime.getFullYear()
      let month = dtime.getMonth() + 1
      if (month < 10) {
        month = '0' + month
      }

      let day = dtime.getDate()
      if (day < 10) {
        day = '0' + day
      }
      let hour = dtime.getHours()
      if (hour < 10) {
        hour = '0' + hour
      }
      let minute = dtime.getMinutes()
      if (minute < 10) {
        minute = '0' + minute
      }
      let second = dtime.getSeconds()
      if (second < 10) {
        second = '0' + second
      }
      return year + '-' + month + '-' + day + ' ' + hour + ': ' + minute + ':' + second
    },
    //查询老人列表方法(新增事件用)
    loadOlderList(){
      let url = 'http://localhost:8080/olders';
      console.log('url = ' + url);
      this.axios.create(
          {
            headers:{
              "Authorization":localStorage.getItem("jwt")
            }
          }
      )
          .get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.olderListOptions = responseBody.data;
        }
      });

    },
    //打开新增事故弹窗(新增事故用)
    openAddNewDialog(){
      this.addNewFormVisible=true;

    },

    //提交新增事故(新增事故用)
    addNewSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let url = 'http://localhost:8080/events/add-new';
          console.log('url = ' + url);
          let formData = this.qs.stringify(this.addNewForm);
          console.log('formData = ' + formData);

          this.axios
              .create(
                  {
                    headers:{
                      "Authorization":localStorage.getItem("jwt")
                    }
                  }
              )
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.$message({
                message: '事故提交成功！',
                type: 'success'
              });
              this.resetForm(formName);
              this.loadEventList();
              this.addNewFormVisible=false;
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //提交修改事故(修改事故用)
    updateSubmitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let formData = this.qs.stringify(this.editForm);
          let url = 'http://localhost:8080/events/'+this.editForm.id+'/pass';

          //如果事故状态是"1",则发出完成事故的指令,改变url
          if(this.editForm.state==1){
            url = 'http://localhost:8080/events/'+this.editForm.id+'/complete';
          }
          console.log('url = ' + url);
          console.log('formData = ' + formData);
          this.axios
              .create(
                  {
                    headers:{
                      "Authorization":localStorage.getItem("jwt")
                    }
                  }
              )
              .post(url, formData).then((response) => {
            let responseBody = response.data;
            if (responseBody.state == 20000) {
              this.$message({
                message: '事故提交成功！',
                type: 'success'
              });
              this.resetForm(formName);
              this.loadEventList();
              this.dialogFormVisible=false;
            } else {
              this.$message.error(responseBody.message);
            }
          });
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },

    //打开修改事故弹窗(修改事故用,同时查询事故详情,编写弹窗的文本)
    openEditDialog(event) {
      this.dialogFormVisible = true;
      this.eventEditTitle=this.eventStateText[event.state];
      this.eventEditLable=this.eventEditLableOptions[event.state];
      let url = 'http://localhost:8080/events/' + event.id;
      console.log('url = ' + url);
      this.axios.create(
              {
                headers:{
                  "Authorization":localStorage.getItem("jwt")
                }
              }
          ).get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.editForm = responseBody.data;
          this.editForm.olderName=event.olderName;
          this.editForm.checkInfo=''
          console.log("修改的对象:{}",this.editForm);

        } else {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadEventList();
            }
          });
        }
      });
    },

    // 打开删除询问弹窗
    openDeleteConfirm(event) {
      console.log(this.tableData);
      console.log(event);
      let message = '此操作将永久删除【' + event.name+ '】事故，是否继续？';
      this.$confirm(message, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(event);
      }).catch(() => {
      });
    },

    //执行删除
    handleDelete(event) {
      console.log(event.id);
      let url = 'http://localhost:8080/events/' + event.id + "/delete";
      console.log('url = ' + url);

      this.axios.create(
          {
            headers:{
              "Authorization":localStorage.getItem("jwt")
            }
          }
      )
          .post(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.$message({
            message: '删除成功！',
            type: 'success'
          });
          this.loadEventList();
        } else if (responseBody.state == 40400) {
          this.$alert(responseBody.message, '警告', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadEventList();
            }
          });

        } else {
          this.$message.error(responseBody.message);
        }
      });
    },

    //加载事故列表,异步请求
    loadEventList() {
      let url = 'http://localhost:8080/events/list';
      console.log('url = ' + url);

      this.axios.create(
          {
            headers:{
              "Authorization":localStorage.getItem("jwt")
            }
          }
      ).get(url).then((response) => {
        let responseBody = response.data;
        if (responseBody.state == 20000) {
          this.tableData = responseBody.data;

        }
        console.log(this.tableData)

      });
    },
    resetForm(formName) {
      this.$refs[formName].resetFields();
    }
  },
  mounted() {
    this.loadEventList();
    this.loadOlderList();

  }
}
</script>